package cn.tedu.tmall.front.content.service.impl;

import cn.tedu.tmall.front.content.dao.repository.impl.ArticleRepository;
import cn.tedu.tmall.front.content.pojo.po.ArticleDetailPO;
import cn.tedu.tmall.front.content.pojo.po.ArticlePO;
import cn.tedu.tmall.front.content.pojo.vo.ArticleItemVO;
import cn.tedu.tmall.front.content.pojo.vo.ArticleVO;
import cn.tedu.tmall.front.content.pojo.vo.PageDataVO;
import cn.tedu.tmall.front.content.service.IArticleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleRepository articleRepository;

    @Override
    public PageDataVO<ArticleItemVO> listArticleByCategoryId(Long categoryId, Integer pageNum, Integer pageSize) {
        PageDataVO<ArticleItemVO> pageDataVO= new PageDataVO<>();
        PageDataVO<ArticlePO> articlePOPageDataVO = articleRepository.listArticleByCategoryId(categoryId, pageNum, pageSize);
        List<ArticleItemVO> articleItemVOList = articleListPO2ItemListVO(articlePOPageDataVO.getList());
        BeanUtils.copyProperties(articlePOPageDataVO,pageDataVO);
        pageDataVO.setList(articleItemVOList);

        return pageDataVO;
    }
    private List<ArticleItemVO> articleListPO2ItemListVO(List<ArticlePO> articlePOS) {

        List<ArticleItemVO> articleItemVOList = new ArrayList<>();
        for (ArticlePO articlePO : articlePOS) {
            ArticleItemVO articleItemVO = new ArticleItemVO();
            BeanUtils.copyProperties(articlePO,articleItemVO);
            articleItemVOList.add(articleItemVO);
        }
        return articleItemVOList;
    }

    @Override
    public ArticleVO getArticleById(Long articleId) {
        ArticlePO articlePO = articleRepository.getArticleById(articleId);
       if(articlePO == null) {
           throw new RuntimeException("该文章不存在");
       }
        ArticleDetailPO articleDetailPO = articleRepository.getArticleDetail(articleId);
       ArticleVO articleVO = new ArticleVO();
       BeanUtils.copyProperties(articlePO,articleVO);
       BeanUtils.copyProperties(articleDetailPO,articleVO);
        return articleVO ;
    }
}
